<template>
  <!-- 新增课程-编辑课程 -->
  <div class="content">
    <h2 class="u-title-h2">课程信息</h2>
    <div class="u-form-box">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="140px"
        class="demo-ruleForm"
      >
        <el-form-item label="课程名称" prop="name">
          <el-input
            v-model="ruleForm.name"
            placeholder="请输入课程名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="课程类型" prop="type">
          <el-select
            v-model="ruleForm.type"
            placeholder="请选择课程类型"
            @change="typeLabel"
          >
            <el-option
              v-for="(item, index) in selectArr.type"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item
          label="所属年级"
          prop="grade"
          :show-message="ruleForm.grade&&ruleForm.grade.length==0"
        >
          <el-cascader
            :options="selectArr.grade"
            v-model="ruleForm.grade"
            class="cascader"
            placeholder="请选择所属年级"
            :props="{ checkStrictly: true }"
            clearable
          ></el-cascader>
        </el-form-item>-->
        <el-form-item
          label="所属年级"
          prop="grade"
          :show-message="ruleForm.grade && ruleForm.grade.length == 0"
        >
          <el-select
            v-model="ruleForm.grade"
            placeholder="请选择年级"
            @change="changeGrade"
          >
            <el-option
              v-for="(item, index) in selectArr.grade"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--  -->
        <el-form-item
          label="所属学期"
          :show-message="ruleForm.grade && gradeCopy"
        >
          <el-select
            v-model="ruleForm.term"
            @change="changeTerm"
            :placeholder="ruleForm.grade ? '请选择学期' : '请先设置年级'"
            :disabled="!ruleForm.grade"
          >
            <el-option
              v-for="(item, index) in selectArr.term"
              :class="{ optionShow: setTermShow(item.label) }"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--  -->

        <el-form-item label="所属科目" prop="subject">
          <el-select v-model="ruleForm.subject" placeholder="请选择所属科目">
            <el-option
              v-for="(item, index) in selectArr.subject"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 单选 -->
        <el-form-item v-show="!ismultiple" label="教材版本" prop="version">
          <el-select
            v-model="ruleForm.version"
            @change="copyVal"
            placeholder="请设置教材版本"
          >
            <el-option
              v-for="(item, index) in selectArr.version"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 多选 -->
        <!-- prop="versionArr" -->
        <el-form-item v-show="ismultiple" label="教材版本" prop="versionArr">
          <el-select
            v-model="ruleForm.versionArr"
            @change="copyVal"
            multiple
            placeholder="请设置教材版本"
          >
            <el-option
              v-for="(item, index) in selectArr.version"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="封面图片"
          prop="cover_path"
          :required="true"
          :show-message="!ruleForm.cover_path"
        >
          <el-upload
            :http-request="uploadImg"
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeUploadImg"
            action
          >
            <img
              v-if="ruleForm.cover_path"
              :src="ruleForm.cover_path"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p class="u-info-text">
            上传封面为.jpg.png格式，建议图片尺寸为800(宽)*378(高)，图片大小不超过5MB。
          </p>
        </el-form-item>
        <el-form-item label="介绍视频">
          <el-upload
            class="avatar-uploader"
            :http-request="uploadVideo"
            :before-upload="beforeUploadVideo"
            :show-file-list="false"
            action
          >
            <video
              v-if="ruleForm.introduction_video"
              :src="ruleForm.introduction_video"
              controls="controls"
              class="avatar"
            ></video>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-progress
            :percentage="percentage"
            v-show="showRentPrise"
          ></el-progress>
        </el-form-item>
        <el-form-item
          label="课程海报"
          prop="poster_path"
          required
          :show-message="!ruleForm.poster_path"
        >
          <el-upload
            class="avatar-uploader"
            :http-request="uploadPoster"
            :before-upload="beforeUploadPoster"
            :show-file-list="false"
            action
          >
            <img
              v-if="ruleForm.poster_path"
              :src="ruleForm.poster_path"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p class="u-info-text">
            上传海报为.jpg.png格式，建议图片尺寸宽度为696，图片大小不超过10MB。
          </p>
        </el-form-item>
        <el-form-item
          label="课程难度"
          prop="level"
          required
          :show-message="!ruleForm.level"
        >
          <div class="u-form-item-rate">
            <el-rate
              v-model="ruleForm.level"
              :colors="colors"
              show-text
              :texts="texts"
            ></el-rate>
          </div>
        </el-form-item>
        <el-form-item label="课程简介">
          <el-input
            type="textarea"
            placeholder="请输入课程简介"
            class="u-textarea"
            v-model="ruleForm.description"
          ></el-input>
        </el-form-item>
        <el-form-item label="班型" prop="class_type">
          <el-select v-model="ruleForm.class_type" placeholder="请选择班型">
            <el-option
              v-for="(item, index) in selectArr.class_type"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否包含实体讲义" prop="has_teaching_materials">
          <el-radio v-model="ruleForm.has_teaching_materials" :label="1"
            >是</el-radio
          >
          <el-radio v-model="ruleForm.has_teaching_materials" :label="0"
            >否</el-radio
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm', 0)"
            >保存</el-button
          >
          <el-button v-if="$route.query.id" @click="submitForm('ruleForm', 1)"
            >保存并发布</el-button
          >
          <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import {
  queyEnumByTableName,
  ossUpload,
  tableInsert
  // tableUpdate
} from '@/api/api.js'
//  import {myEnumsMixins} from '@/utils/mixins'
import { getCourseById, updateCourse } from '@/api/course.js'
import { ossUploadFile } from '@/api/mixins'
export default {
  name: 'add-update-class',
  data () {
    var levelRule = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择难度'))
      } else {
        callback()
      }
    }
    return {
      isOpen: false,
      gradeCopy: null,
      gradeLabel: '全部',
      showRentPrise: false,
      percentage: 0,
      ismultiple: false,
      selectArr: {
        type: [],
        grade: [],
        subject: [],
        version: [],
        status: [],
        term: [],
        class_type: []
      },
      texts: ['简单', '简单', '一般', '一般', '困难'],
      value2: null,
      colors: ['#99A9BF', '#F7BA2A', 'red'],
      ruleForm: {
        name: '',
        type: '',
        grade: '',
        subject: '',
        version: '',
        versionArr: [],
        cover_path: '',
        poster_path: '',
        level: 0,
        description: '',
        introduction_video: '',
        status: 0,
        term: '',
        has_teaching_materials: 1,
        class_type: '' // 班型
      },
      rules: {
        has_teaching_materials: [
          { required: true, message: '是否包含实体讲义', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
          // { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择课程分类', trigger: 'change' }
        ],
        grade: [
          {
            required: true,
            message: '请选择年纪',
            trigger: 'change'
          }
        ],
        subject: [{ required: true, message: '请选择科目', trigger: 'change' }],
        versionArr: [
          {
            type: 'array',
            required: true,
            message: '请选择教材版本(多选)',
            trigger: 'change'
          }
        ],

        term: [{ required: true, message: '请选择学期', trigger: 'change' }],
        version: [
          { required: true, message: '请选择教材版本', trigger: 'change' }
        ],
        cover_path: [
          { required: true, message: '请上传封面', trigger: 'change' }
        ],
        poster_path: [
          { required: true, message: '请上传海报', trigger: 'change' }
        ],
        level: [{ validator: levelRule, trigger: 'change' }]
      }
    }
  },
  watch: {},
  created () {
    // if (!this.$route.query.id) {
    //   this.getSelectData()
    // }
  },
  activated () {
    // if (this.$route.query.id) {
    this.getSelectData()
    // }
  },
  methods: {
    changeTerm (e) {
      this.gradeCopy = e
    },
    changeGrade (e, carate) {
      if (carate !== 'carate') {
        this.ruleForm.term = ''
      }
      if (e === null) {
        this.gradeLabel = '全部'
      } else {
        this.selectArr.grade.map(item => {
          if (item.value === e) {
            this.gradeLabel = item.label
          }
        })
      }
    },
    setTermShow (e) {
      if (this.gradeLabel === '全部') {
        return false
      }
      let text = this.gradeLabel.substr(0, 1)
      let eText = e.substr(0, 1)
      let newText = '升' + text
      // console.log(text, eText, newText)
      if (text === eText && e.indexOf('升') === -1) {
        return false
      } else if (e.indexOf(newText) !== -1) {
        return false
      } else if (text === '七' && e === '小升初') {
        return false
      } else {
        return true
      }
      //
    },
    copyVal (e) {
      if (e) {
        this.ismultiple
          ? (this.ruleForm.version = this.ruleForm.versionArr[0])
          : (this.ruleForm.versionArr = [this.ruleForm.version])
      }
    },
    typeLabel (e) {
      this.ismultiple = false
      // console.log(e, this.selectArr.type)
      this.selectArr.type.map(item => {
        if (item.value === e && item.label === '专题特训课') {
          this.ismultiple = true
          // if (this.ruleForm.version) {
          //   this.ruleForm.versionArr = [].concat(this.ruleForm.version)
          // }
        }
      })
    },
    // 获取下拉菜单数据
    async getSelectData () {
      this.gradeCopy = null
      this.ruleForm = {
        name: '',
        type: '',
        grade: '',
        subject: '',
        version: '',
        versionArr: [],
        cover_path: '',
        poster_path: '',
        level: 0,
        description: '',
        introduction_video: '',
        status: 0,
        term: '',
        has_teaching_materials: 1,
        class_type: ''
      }
      this.$refs.ruleForm.resetFields()
      let res = await queyEnumByTableName({ tableName: 'nice_course' })
      if (res[0]) {
        return
      }
      let arr = res[1].data
      Object.keys(this.selectArr).forEach(item => {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].fieldName === item) {
            this.selectArr[item] = arr[i].child
          }
        }
      })
      this.selectArr = JSON.parse(
        JSON.stringify(this.selectArr)
          .split('display_value')
          .join('label')
          .split('child')
          .join('children')
          .split('t_id')
          .join('value')
      )
      // 根据id获取课程信息
      // console.log(this.selectArr)
      if (this.$route.query.id) {
        this.getCourseByIdFn()
      }
    },
    // 根据id获取课程信息
    async getCourseByIdFn () {
      let res = await getCourseById({
        table_name: 'nice_course',
        id: this.$route.query.id
      })
      if (res[0]) {
        return
      }
      let data = res[1].data
      console.log(data, 'asdasdasdsadsads')
      this.ruleForm.name = data.name
      this.ruleForm.type = data.type
      this.ruleForm.grade = data.grade
      this.gradeCopy = data.grade
      this.ruleForm.term = data.term
      this.ruleForm.subject = data.subject
      this.ruleForm.cover_path = data.cover_path
      this.ruleForm.poster_path = data.poster_path
      this.ruleForm.level = data.level
      this.ruleForm.description = data.description
      this.ruleForm.introduction_video = data.introduction_video
      this.ruleForm.has_teaching_materials = data.has_teaching_materials
      this.ruleForm.class_type = data.class_type
      this.changeGrade(this.ruleForm.grade, 'carate')
      let arr = data.version.split(',')
      let newArr = []
      arr.map(item => {
        newArr.push(parseInt(item))
      })
      this.ruleForm.versionArr = [...newArr]
      this.ruleForm.version = newArr[0]
      console.log(this.ruleForm, 'arrarrarrarr')
      this.typeLabel(data.type)
    },

    // 上传封面至oss请求
    async uploadImg (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'COURSE_COVER')
      if (res[0]) {
        return
      }
      this.ruleForm.cover_path = res[1].data.url
    },
    // 上传封面oss请求
    async uploadPoster (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'COURSE_VEDIOS')
      if (res[0]) {
        return
      }
      this.ruleForm.poster_path = res[1].data.url
    },
    // 上传视频oss请求
    async uploadVideo (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let url = await ossUploadFile(this, e, 'COURSE_VEDIOS')
      this.ruleForm.introduction_video = url
    },
    // 上传封面前验证
    beforeUploadImg (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传的封面图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传的封面图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上传海报前验证
    beforeUploadPoster (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isJPG) {
        this.$message.error('上传的海报图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传的封面图片大小不能超过 5MB!')
      }
      return isJPG && isLt2M
    },
    // 上传视频前验证
    beforeUploadVideo (file) {
      // let aaa = true
      // return aaa
    },

    progress (percentage, checkpoint, res) {
      this.percentage = parseInt(percentage * 100)
    },
    // 表单验证
    // 新增课程信息请求
    async addCoures () {
      let version
      this.ismultiple
        ? (version = this.ruleForm.versionArr.join(','))
        : (version = this.ruleForm.version)
      let res = await tableInsert([
        {
          table_name: 'nice_course',
          list: [
            {
              // code: this.randomString(), // --编码
              name: this.ruleForm.name, // --
              type: this.ruleForm.type, // -- 分类
              grade: this.ruleForm.grade, // -- 年级
              subject: this.ruleForm.subject, // -- 科目
              version: version, // -- 版本
              // time: 8, // --
              cover_path: this.ruleForm.cover_path,
              term: this.ruleForm.term,
              introduction_video: this.ruleForm.introduction_video,
              poster_path: this.ruleForm.poster_path,
              level: this.ruleForm.level, // -- 课程难度
              description: this.ruleForm.description, // --简介
              status: this.ruleForm.status, // --  0 保存 1 保存并发布
              has_teaching_materials: this.ruleForm.has_teaching_materials,
              class_type: this.ruleForm.class_type
            }
          ]
        }
      ])
      if (res[0]) {
        return
      }
      this.$router.push({ name: 'class-list' })
      console.log(res[1])
    },
    // 修改课程信息请求
    async updateCoures () {
      let version
      this.ismultiple
        ? (version = this.ruleForm.versionArr.join(','))
        : (version = this.ruleForm.version)
      let res = await updateCourse([
        {
          table_name: 'nice_course',
          update: [
            {
              name: this.ruleForm.name, // --
              type: this.ruleForm.type, // -- 分类
              grade: this.ruleForm.grade, // -- 年级
              subject: this.ruleForm.subject, // -- 科目
              version: version, // -- 版本
              // time: 8, // --
              term: this.ruleForm.term,
              cover_path: this.ruleForm.cover_path,
              introduction_video: this.ruleForm.introduction_video,
              poster_path: this.ruleForm.poster_path,
              level: this.ruleForm.level, // -- 课程难度
              description: this.ruleForm.description, // --简介
              status: this.ruleForm.status, // --  0 保存 1 保存并发布
              has_teaching_materials: this.ruleForm.has_teaching_materials,
              class_type: this.ruleForm.class_type
            }
          ],
          where: [
            {
              id: this.$route.query.id
            }
          ]
        }
      ])
      if (res[0]) {
        return
      }
      this.$router.push({ name: 'class-list' })
      console.log(res[1])
    },

    submitForm (formName, e) {
      this.ruleForm.status = e
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(1)
          // 新增课程
          if (!this.$route.query.id) {
            this.addCoures()
          } else {
            // 修改课程
            this.updateCoures()
          }
        } else {
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    randomString () {
      let len = 7
      let $chars =
        'ABCDEFGHJKMNPQRSTWXYZ0123456789' /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      let maxPos = $chars.length
      let pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    }
  }
}
</script>
<style scoped>
h2 {
  padding-left: 20px;
}
.u-form-box {
  width: 670px;
  padding-bottom: 50px;
}
.u-form-item-rate {
  padding-top: 9px;
}
.cascader {
  width: 100%;
}
.u-title-h2 {
  padding-left: 70px;
  margin-bottom: 40px;
}
.optionShow {
  display: none;
}
.u-info-text {
  font-size: 12px;
}
</style>
